from flask import Flask, render_template, request, send_from_directory
import algorList
import json
import xiachufang
import os

app = Flask(__name__, static_url_path='')


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/show/<id>')
def show(id):
    data = algorList.getList(id)
    returnData = {
        "id": id,
        "data": data
    }
    return render_template('show.html', data=returnData)


@app.route('/intro')
def intro():
    return render_template('intro.html')

@app.route('/resume')
def resume():
    return render_template('resume.html')

@app.route('/getStockList')
def getStockList():
    data = algorList.getList("0")
    return json.dumps(data)


@app.route('/getStockData')
def getStockData():
    code = request.args.get("c")
    type = request.args.get("t")
    area = request.args.get("a")
    list = algorList.getSingleOnline(code, type, area)
    return json.dumps({
        "flag": "1",
        "data": list
    })


@app.route('/addWareHouse')
def addWareHouse():
    name = request.args.get("name")
    code = request.args.get("code")
    price = request.args.get("price")
    exist = algorList.existWareHouse(code)
    if not exist:
        add = algorList.addWareHouse(code, name, price)
        return json.dumps({
            "flag": "1"
        }) if add else json.dumps({
            "flag": "0"
        })
    else:
        return json.dumps({
            "flag": "1"
        })

@app.route('/removeWareHouse')
def removeWareHouse():
    code = request.args.get("code")
    remove = algorList.removeWareHouse(code)
    return json.dumps({
        "flag": "1"
    }) if remove else json.dumps({
        "flag": "0"
    })

# 获取下厨房菜品种类
@app.route('/SPcategory')
def getcategory():
    data = xiachufang.getCategory()
    return json.dumps(data)


# 获取菜谱单个种类菜品列表
@app.route('/SPcateList')
def getcatelist():
    id = request.args.get('id')
    page = request.args.get('page')
    data = xiachufang.getCateList(id, page)
    return json.dumps(data)


# 获取菜谱推荐
@app.route('/SPrecommandList')
def getrecommandlist():
    page = request.args.get('page')
    data = xiachufang.recommand(page)
    return json.dumps(data)


# 菜谱搜索
@app.route('/SPsearchList')
def getsearchlist():
    word = request.args.get('word')
    page = request.args.get('page')
    data = xiachufang.searchBywords(word, page)
    return json.dumps(data)


# 获取菜品详情
@app.route('/SPcookDetail')
def getcookdetail():
    id = request.args.get('id')
    data = xiachufang.getDetail(id)
    return json.dumps(data)


# 获取关键词推荐
@app.route('/getKeywords')
def getKeywords():
    data = xiachufang.getKeywords()
    return json.dumps(data)


# 下载app
@app.route('/download/<path:filename>')
def downloader(filename):
    dirpath = os.path.join(app.root_path, 'static/download')
    return send_from_directory(dirpath, filename, as_attachment=True)


if __name__ == '__main__':
    app.run()
